﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InformationText : MonoBehaviour {
    public static InformationText informationText
    {
        get
        {
            if (_informationText == null)
            {
                _informationText = FindObjectOfType<InformationText>();
            }
            return _informationText;
        }
    }
    static InformationText _informationText;
    public Text text;
    RectTransform rectTransform;
    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
    }
    private void Start()
    {
        informationText.gameObject.SetActive(false);
    }
    public static void ShowInformation(string s,RectTransform contentRectTransform)
    {
        informationText.gameObject.SetActive(true);
        informationText.text.text = s;
        informationText.rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)1, informationText.text.preferredHeight);
        informationText.transform.position = SetPosition(contentRectTransform, informationText.rectTransform);
    }

    public static void Exit()
    {
        informationText.gameObject.SetActive(false);
        informationText.text.text = "";
    }

    static Vector3 SetPosition(RectTransform contentRecTransform,RectTransform textRectTransform)
    {
        Vector2 viewPortPoint = Camera.main.ScreenToViewportPoint(contentRecTransform.position);
        Vector3 textPosition = contentRecTransform.position;
        Vector2 size = new Vector2(contentRecTransform.rect.width, contentRecTransform.rect.height);
        Vector2 textSize = new Vector2(textRectTransform.rect.width, textRectTransform.rect.height);
        if (viewPortPoint.x > 0.5f)
        {
            textPosition.x -= (size.x + textSize.x) * 0.5f;
        }
        else
        {
            textPosition.x += (size.x + textSize.x) * 0.5f;
        }
        if (viewPortPoint.y > 0.5)
        {
            textPosition.y -= (size.y + textSize.y) * 0.5f;
        }
        else
        {
            textPosition.y += (size.y + textSize.y) * 0.5f;
        }
        return textPosition;
    }
}
